import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";
import ElementUI from "element-ui";
import "normalize.css/normalize.css";
import "element-ui/lib/theme-chalk/index.css";
import "@/icons";
import "@/styles/index.scss"; // 全局样式
import "@/assets/css/layout.scss";
import api from "./api/api.js";
import { getToken, removeToken } from "@/utils/auth.js";
import moment from "moment";

window.$store = store;
Vue.prototype.$api = api;
Vue.use(ElementUI);

Vue.config.productionTip = false;

// 不重定向白名单
const whiteList = [
  "/login",
  "/forget"
];

router.beforeEach((to, from, next) => {
  // 有token
  if (getToken()) {

    // 进入登录页重定向首页
    if (to.path === "/login") {
      next({ path: "/" });
    } else {
      next();
      // console.log(Object.keys(store.getters.userInfo),"Object.keys(store.getters.userInfo")
      if ((Object.keys(store.getters.userInfo)).length === 0) {
        store.dispatch("GetInfo").then(res => { // 拉取用户信息
          next();
        }).catch((err) => {
          api.login.loginOut().then((res) => {
            if (res.code === 200) {
              store.commit("setToken", "");
              removeToken();
              next({ path: "/login" });
              location.reload();
            }
          })
            .catch(err => {
              removeToken();
              store.commit("setToken", "");
              next({ path: "/login" });
              location.reload();
            });
        });
      } else {
        console.log(store.getters.userInfo.isSecuritySettings);
        console.log("to.path", to.path);
        // todo 0 未完善信息
        if (store.getters.userInfo.isSecuritySettings == 0) {
          setTimeout(()=>{
            next({ path: "/completeUserInfo" });
          },300)
        } else {
          next();
        }
      }

    }

  } else {
    if (whiteList.includes(to.path)) {
      next();
    } else {
      next({ path: "/login" });
    }
  }
});

const formatTime = (value) => {
  if (value) {
    value = Number(value);
    return moment(value).format("YYYY-MM-DD HH:mm:ss");
  } else {
    return 0;
  }
};

Vue.filter("formatTime", formatTime);

new Vue({
  router,
  store,
  render: h => h(App),
}).$mount("#app");
